package com.kinsin.kinsinutil

import java.text.SimpleDateFormat
import java.util.*

/**
 * 时间工具类
 * @author kinsin
 */
object TimeUtils {
    // 预定义时区常量
    private val BEIJING_TIMEZONE = TimeZone.getTimeZone("Asia/Shanghai") // 东八区
    private val UTC_TIMEZONE = TimeZone.getTimeZone("UTC")

    // 常用日期格式
    const val FORMAT_YYYY_MM_DD = "yyyy-MM-dd"
    const val FORMAT_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"
    const val FORMAT_HH_MM_SS = "HH:mm:ss"

    // region 时间戳获取
    /**
     * 获取当前时间戳（毫秒）
     */
    fun getCurrentTimestamp(): Long = System.currentTimeMillis()

    /**
     * 获取当前时间戳（秒）
     */
    fun getCurrentTimestampInSeconds(): Long = System.currentTimeMillis() / 1000
    // endregion

    // region 时间格式化/解析（东八区）
    /**
     * 格式化时间戳为东八区时间字符串
     * @param format 默认格式：yyyy-MM-dd HH:mm:ss
     */
    @JvmOverloads
    fun formatTimestamp(
        timestamp: Long,
        format: String = FORMAT_YYYY_MM_DD_HH_MM_SS,
        timeZone: TimeZone = BEIJING_TIMEZONE
    ): String {
        return try {
            createFormatter(format, timeZone)?.format(Date(timestamp)) ?: ""
        } catch (e: Exception) {
            ""
        }
    }

    /**
     * 解析东八区时间字符串为时间戳
     * @param format 默认格式：yyyy-MM-dd HH:mm:ss
     */
    @JvmOverloads
    fun parseFormattedTime(
        timeString: String,
        format: String = FORMAT_YYYY_MM_DD_HH_MM_SS,
        timeZone: TimeZone = BEIJING_TIMEZONE
    ): Long {
        return try {
            createFormatter(format, timeZone)
                ?.parse(timeString)
                ?.time ?: 0L
        } catch (e: Exception) {
            0L
        }
    }

    /**
     * 获取当前东八区时间
     * @param format 默认格式：yyyy-MM-dd HH:mm:ss
     */
    @JvmOverloads
    fun getCurrentFormattedTime(format: String = FORMAT_YYYY_MM_DD_HH_MM_SS): String {
        return formatTimestamp(getCurrentTimestamp(), format)
    }
    // endregion

    // region 时间差计算（与时区无关）
    fun calculateTimeDifferenceInSeconds(
        time1: String,
        time2: String,
        format: String
    ): Long {
        val date1 = parseFormattedTime(time1, format)
        val date2 = parseFormattedTime(time2, format)
        return abs((date1 - date2) / 1000)
    }

    fun getTimeDifferenceInMillis(start: Long, end: Long): Long = abs(end - start)
    fun getTimeDifferenceInSeconds(start: Long, end: Long): Long = abs((end - start) / 1000)
    fun getTimeDifferenceInMinutes(start: Long, end: Long): Long = abs((end - start) / (1000 * 60))
    fun getTimeDifferenceInHours(start: Long, end: Long): Long = abs((end - start) / (1000 * 60 * 60))
    fun getTimeDifferenceInDays(start: Long, end: Long): Long = abs((end - start) / (1000 * 60 * 60 * 24))
    // endregion

    // region 持续时间格式化
    fun formatDuration(seconds: Int): String {
        return when {
            seconds < 0 -> "无效时长"
            seconds == 0 -> "00秒"
            else -> {
                val hours = seconds / 3600
                val remaining = seconds % 3600
                val minutes = remaining / 60
                val secs = remaining % 60

                buildString {
                    if (hours > 0) append("%02d时".format(hours))
                    if (minutes > 0 || hours > 0) append("%02d分".format(minutes))
                    append("%02d秒".format(secs))
                }
            }
        }
    }
    // endregion

    // region 私有方法
    private fun createFormatter(pattern: String, timeZone: TimeZone): SimpleDateFormat? {
        try {
            return SimpleDateFormat(pattern, Locale.getDefault()).apply {
                this.timeZone = timeZone
            }
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        }
    }

    private fun abs(value: Long) = if (value < 0) -value else value
    // endregion
}